// wire.cpp
#include "wire.h"
#include <QPainterPath>

Wire::Wire(QGraphicsItem *parent) : QGraphicsPathItem(parent),
    m_startComponent(nullptr), m_endComponent(nullptr)
{
    m_pen.setWidth(2);
    m_pen.setColor(Qt::black);
    setPen(m_pen);
    setZValue(-1); // 确保线在组件下方
}

void Wire::setStartComponent(Component *component)
{
    m_startComponent = component;
}

void Wire::setEndComponent(Component *component)
{
    m_endComponent = component;
}

void Wire::setStartPos(const QPointF &pos)
{
    m_startPos = pos;
    m_points.clear();
    m_points.append(pos);
    updatePath();
}

void Wire::setEndPos(const QPointF &pos)
{
    m_endPos = pos;
    if (m_points.size() < 2)
        m_points.append(pos);
    else
        m_points.last() = pos;
    updatePath();
}

void Wire::addPoint(const QPointF &point)
{
    if (m_points.size() < 2) {
        m_points.append(point);
    } else {
        m_points.last() = point;
    }
    updatePath();
}

Component *Wire::startComponent() const
{
    return m_startComponent;
}

Component *Wire::endComponent() const
{
    return m_endComponent;
}

QPointF Wire::startPos() const
{
    return m_startPos;
}

QPointF Wire::endPos() const
{
    return m_endPos;
}

void Wire::updatePath()
{
    QPainterPath path;
    if (m_points.isEmpty()) return;

    path.moveTo(m_points.first());
    for (int i = 1; i < m_points.size(); ++i) {
        path.lineTo(m_points[i]);
    }

    setPath(path);
}
